package com.estock.platform.http.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import com.estock.platform.http.request.StockClientRequest;
import com.estock.platform.http.response.JSONResponse;
import com.estock.platform.http.response.ResponseFactory;
import com.estock.platform.http.utils.RequestUtil;

public class URLConnectionClient extends AbstractURLConnectClient {
	
	@Override
	public <T extends JSONResponse> T execute(StockClientRequest request,
			Map<String, String> headers, String requestMethod,
			Class<T> responseClass) throws Exception {
		InputStream inputStream = getInputStream(request, headers, requestMethod);
		String responseBody = saveStreamAsString(inputStream);
		return ResponseFactory.createCustomResponse(
				responseBody, contentType, responseCode, responseClass);
	}

	/**
	 * you may override this method by replacing saveStreamAsUTF8 as
	 * saveStreamAsGBK for specail case of reading inputstream of GBK charset.
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	protected String saveStreamAsString(InputStream inputStream)
			throws IOException {
		return RequestUtil.saveStreamAsUTF8(inputStream);
	}


}
